package im.yisme.view.ui;

import im.yisme.R;
import im.yisme.view.activities.RecordActivity;
import im.yisme.view.service.RecordViewService;
import im.yisme.view.ui.animation.Comet;
import im.yisme.view.ui.animation.Door;
import im.yisme.view.ui.animation.DoorRecord;
import im.yisme.view.ui.animation.Halo;
import im.yisme.view.ui.animation.Tail;
import im.yisme.view.ui.animation.pojo.DoorPOJO;
import im.yisme.view.ui.animation.pojo.HaloPOJO;
import im.yisme.view.ui.animation.pojo.LineBitmapPOJO;
import im.yisme.view.ui.animation.pojo.LinePOJO;
import im.yisme.view.ui.component.ComponentInvolved;
import im.yisme.view.ui.component.YButton;
import im.yisme.view.ui.component.YComponent;
import im.yisme.view.ui.util.UIparams;

import java.util.ArrayList;
import java.util.Iterator;

import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;

/**
 * 负责录制用例的界面绘制
 * 
 * @author Max
 * 
 */
public class RecordView extends SurfaceView implements SurfaceHolder.Callback,RecordViewService,ComponentInvolved {

	private SurfaceHolder holder;
	private RecordActivity activity;
	
	//-------------------------------------------------
	private PaintThread paintThread;
	// 手势轨迹消除线程
	private Tail tailThread;
	// 点击反馈线程队列
	private ArrayList<Halo> haloThreadArrayList;
	// 手势反馈线程队列
	private ArrayList<Comet> cometThreadArrayList;
	// 加载效果线程
	private DoorRecord doorThread;
	//-------------------------------------------------
	
	
	//-------------------------------------------------
	//常量
	
	public static final int PAUSE_POLLING_INTERVAL= 500;
	private static final int PAINT_REFRESH_INTERVAL = 1;
	private static final int MAX_LENGTH_OF_TRACK=10;	
    //--------------------------------------------------
	
	
	// --------------------------------------------------------
	// 6个圆点
	
	private int r = 80;
	private RectF[] pillar = new RectF[UIparams.NUM_OF_PILLAR];
	private Bitmap pillarBitmap;
	
	// 加载界面
	private DoorPOJO door;
	private boolean loadCompletion;
	// --------------------------------------------------------

	
	// --------------------------------------------------------
	// 点击反馈动画队列
	private ArrayList<HaloPOJO> haloArrayList;
	// 手势反馈动画队列
	private ArrayList<LineBitmapPOJO> cometArrayList;
	// 手势轨迹动画队列
	private ArrayList<LinePOJO> trackArrayList;
	private boolean isBeginTrack;//轨迹开始标志
	//---------------------------------------------------------
	
	// --------------------------------------------------------
	// 组件
	private ArrayList<YButton> buttonList;
	//  背景
		private Bitmap bgp,bgp1,bgp2,bgp3;
		private int index;
		private int count;
	    private static final int NUM_OF_BGP=3;
	//---------------------------------------------------------
	
	

	public RecordView(Context context,RecordActivity activity) {
		super(context);
		this.activity = activity;
		//初始化
		init();
	}

	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        stop();
	}
	
	//-----------------------------------------------------------
	// 对RecordActivity提供的接口
	public void start(){
		
		paintThread=new PaintThread(holder);
		paintThread.start();
		
		tailThread=new Tail(trackArrayList);
		tailThread.start();
	}
	public void pause(){
		tailThread.pauseRunning();
		
		Iterator<Halo> it=haloThreadArrayList.iterator();
		while (it.hasNext()) {
			Halo halo = it.next();
			halo.pauseRunning();
		}
	}
	public void resume(){
		tailThread.resumeRunning();
		
		Iterator<Halo> it=haloThreadArrayList.iterator();
		while (it.hasNext()) {
			Halo halo = it.next();
			halo.resumeRunning();
		}
	}
	public void stop(){
		paintThread.stopRunning();
		tailThread.stopRunning();
	}
	public void addNewMovePoint(PointF point){
		PointF lastPoint;
		if(isBeginTrack || trackArrayList.size() == 0){
			lastPoint=point;
			isBeginTrack=false;
		}
		else 
			lastPoint=trackArrayList.get(0).getHead();
		
		LinePOJO tempLinePOJO=new LinePOJO(point, lastPoint);
		trackArrayList.add(0, tempLinePOJO);
		
		if(trackArrayList.size()>MAX_LENGTH_OF_TRACK) trackArrayList.remove(MAX_LENGTH_OF_TRACK);
	}
	public void setTrackBegin(){
		isBeginTrack=true;
	}
	public void finishLoading(){
		loadCompletion = true;
		activity.start();
	}
	//-----------------------------------------------------------
	
	
	//------------------------------------------------------------
	//对外提供接口
		public void validTap(int whichPillar) {
			// TODO Auto-generated method stub
			Halo halo=new Halo(new PointF(UIparams.center[whichPillar][0],
                    					  UIparams.center[whichPillar][1]),
                    					  r,
                    					  haloArrayList,haloThreadArrayList,
                    					  getResources());
			halo.start();

		}
		
		public void addYButton(YButton button) {
			// TODO Auto-generated method stub
			buttonList.add(button);
		}
		public void comet(int points[],long bestTime,boolean isActive){
			
			for(int i=0;i<points.length;i++){
				points[i] = (points[i]+1) * (points[i]+1);
			}
			Comet comet=new Comet(bestTime, 
					              points, 
					              cometArrayList, 
					              cometThreadArrayList,
					              getResources());
			
			if(isActive) comet.living();
			else comet.dead();
			
			comet.start();
		}
	//------------------------------------------------------------
		
		
	// ----------------------------------------------------------------
	// 绘图线程
	class PaintThread extends Thread {

		private SurfaceHolder holder;
		private boolean isRunning;
		private boolean pause;
		
		public PaintThread(SurfaceHolder holder) {
			super();
			this.holder = holder;
			isRunning = true;
		}

		public void run() {
			super.run();

			while (isRunning) {
				
				

				Canvas canvas = null;
				try {
					//暂停
					while(pause){
						Thread.sleep(PAUSE_POLLING_INTERVAL);
					}
					//绘图
					synchronized (holder) {
						canvas = holder.lockCanvas();
						canvas.setDrawFilter(new PaintFlagsDrawFilter(0,
								Paint.ANTI_ALIAS_FLAG
										| Paint.FILTER_BITMAP_FLAG));


						Paint p = new Paint();
						
						if(loadCompletion){	
						if(!activity.pause)	count++;
						if(count == 7){
							index = (index+1)%(NUM_OF_BGP+1);
							count = 0;
							bgp = getBGP(index);
						}
						
						
						if(bgp != null)
						canvas.drawBitmap(bgp, 0, 0, p);
						
						//----------------------------------
						// 画手势提示轨迹Comet
						
						int size1 = cometArrayList.size();
						for(int i=0;i<size1;i++){
							
							LineBitmapPOJO linePOJO;
							try {
								linePOJO = cometArrayList.get(i);
							} catch (Exception e) {
								// TODO: handle exception
								continue;
							}

							ArrayList<Bitmap> lines = linePOJO.getLines();
							ArrayList<PointF> points = linePOJO.getPoints();
							
							p.setAlpha(linePOJO.getAlpha());
							
							int length = lines.size();
							for(int j=0;j<length;j++){
								canvas.drawBitmap(lines.get(j), points.get(j).x, points.get(j).y, p);
							}	
						}
						//----------------------------------
						
						p.setAlpha(255);
						// ---------------------------------
						// 画六个柱子
						
						for (RectF r : pillar) {
							
							canvas.drawBitmap(pillarBitmap, r.left, r.top, p);
						}
						// ---------------------------------

						//----------------------------------
						// 画Halo
						p.setColor(Color.GREEN);
						p.setStrokeWidth(3);
						p.setStyle(Paint.Style.FILL);
						
						Iterator<HaloPOJO> itHalo=haloArrayList.iterator();
						while(itHalo.hasNext()){
							HaloPOJO halo=itHalo.next();
							p.setAlpha(halo.getAlpha());
							Bitmap haloBitmap = halo.getHalo();
							PointF point = halo.getHaloPointF();
							
							canvas.drawBitmap(haloBitmap, point.x, point.y, p);
						}
						//----------------------------------
						
						//----------------------------------
						// 画手势轨迹
						p.setColor(Color.YELLOW);
						
						Iterator<LinePOJO> itTail=trackArrayList.iterator();
						int lineAlpha=255;
						while (itTail.hasNext()) {
							LinePOJO line = itTail.next();
							p.setAlpha(lineAlpha);
							
							canvas.drawLine(line.getHead().x, line.getHead().y, 
									        line.getTail().x, line.getTail().y, 
									        p);
							
							lineAlpha=lineAlpha-(255/MAX_LENGTH_OF_TRACK);							
						}
						//----------------------------------
						
						
						//----------------------------------
						//暂停幕布
						if(activity.pause){
							p.setColor(Color.BLACK);
							p.setAlpha(100);
							canvas.drawRect(new RectF(0, 0, UIparams.screenWidth, UIparams.screenHeight), p);
						}
						//----------------------------------
						
						
						//----------------------------------
						// 画组件

						
						Iterator<YButton> itButton=buttonList.iterator();
						while (itButton.hasNext()) {
							YButton yButton = itButton.next();
							if(!yButton.isVisible()) continue;
							
							if(yButton.getBGP() != null) canvas.drawBitmap(yButton.getBGP(), yButton.getX(), yButton.getY(), p);
							
						}
						//----------------------------------
						
						}
						// ---------------------------------
						// 加载界面
						if(door.getRightPoint() != null){
							 PointF left = door.getLeftPoint();
							 PointF right = door.getRightPoint();
							 Bitmap door_left = door.getDoor_left();
							 Bitmap door_right = door.getDoor_right();
							 
							 p.setTextSize(30);
							 
							 canvas.drawBitmap(door_right, right.x, right.y, p);
							 canvas.drawBitmap(door_left, left.x, left.y, p);
							 
							 Rect rect = new Rect();
							 String text = door.getLoadingText();
							 p.getTextBounds(text, 0, text.length(), rect);
							 
							 canvas.drawText(text, 395-rect.width()/2, 255 - rect.height()/2, p);
					
						}
						else {
							doorThread.stopRunning();
						}
						// ---------------------------------
						
						
						Thread.sleep(PAINT_REFRESH_INTERVAL);

					}
				} catch (Exception e) {
					// TODO: handle exception
				} finally {
					if (canvas != null) {
						holder.unlockCanvasAndPost(canvas);

					}
				}
			}
		}
		public void stopRunning(){
			isRunning=false;
		}
		public void pauseRunning(){
			pause=true;
		}
		public void resumeRunning(){
			pause=false;
		}

	}

	//私有方法

	private void initPillar() {
		for (int i = 0; i < UIparams.NUM_OF_PILLAR; i++) {
			pillar[i] = new RectF(UIparams.center[i][0] - r, UIparams.center[i][1] - r,
					              UIparams.center[i][0] + r, UIparams.center[i][1] + r);
		}

		pillarBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.game_pillar);
	}
	
	private void init(){
		holder = this.getHolder();
		holder.addCallback(this);
        trackArrayList=new ArrayList<LinePOJO>();
        haloArrayList=new ArrayList<HaloPOJO>();
        cometArrayList = new ArrayList<LineBitmapPOJO>();
        haloThreadArrayList=new ArrayList<Halo>();
        cometThreadArrayList = new ArrayList<Comet>();
        buttonList=new ArrayList<YButton>();
        isBeginTrack=true;
        initPillar();
        initBitmap();
        
        door = new DoorPOJO();
        doorThread = new DoorRecord(door, getResources(), this);
        doorThread.start();
	}
	private void initBitmap(){
		bgp1 = BitmapFactory.decodeResource(getResources(), R.drawable.game_bgp1);
		bgp2 = BitmapFactory.decodeResource(getResources(), R.drawable.game_bgp2);
		bgp3 = BitmapFactory.decodeResource(getResources(), R.drawable.game_bgp3);
		bgp = bgp1;
	}

	private Bitmap getBGP(int index){
		Bitmap bm = null;
		switch (index) {
		case 0:
			bm = bgp1;
			break;
		case 1:
			bm = bgp2;
			break;
		case 2:
			bm = bgp3;
			break;
		case 3:
			bm = bgp2;
			break;
		default:
			break;
		}
		
		return bm;
	}

	

}
